package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.ItemVO;
import com.atguigu.gulimall.ware.vo.MergePurchaseVO;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0)
                .or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergePurchaseVO mergePurchaseVO) {
        //确认采购单状态是0或者1
        List<Long> items = mergePurchaseVO.getItems();
        for (Long purchaseDetailId : items) {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(purchaseDetailId);
            if (!(detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())) {
                throw new RuntimeException("采购项ID：" + detailEntity.getId() + "的状态不是新建(0)或者已分配(1)，不符合要求");
            }
        }

        Long purchaseId = mergePurchaseVO.getPurchaseId();
        //合并到指定采购单
        if (purchaseId == null) {
            //新建采购单，然后再合并
            //1、新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //0 新建状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //2、建立采购单和采购单明细的关联
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(purchaseDetailId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseDetailId);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        //3、更新采购单更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 采购人员领取采购单
     *
     * @param purchaseIds 采购单ids
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> purchaseIds) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = this.listByIds(purchaseIds);
        purchaseEntities = purchaseEntities.stream()
                .filter(purchaseEntity ->
                        purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.CREATED.getCode()) ||
                                purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                .map(purchaseEntity -> {
                    purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    purchaseEntity.setUpdateTime(new Date());
                    return purchaseEntity;
                })
                .collect(Collectors.toList());
        //2、改变采购单的状态
        this.updateBatchById(purchaseEntities);

        //3、改变采购项(purchase_detail)的状态为：正在采购
        purchaseEntities.forEach(purchaseEntity -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(
                    new QueryWrapper<PurchaseDetailEntity>()
                            .eq("purchase_id", purchaseEntity.getId()));
            List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
                //修改状态
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(purchaseDetailEntity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        //1、改变采购单状态
        Long id = purchaseDoneVO.getId();
        //2、改变采购项的状态
        Boolean flag = true;
        List<ItemVO> items = purchaseDoneVO.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (ItemVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            //如果有一个采购项不成功，返回false
            if (WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode() == item.getStatus()) {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
                flag = false;
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3、将成功的采购进行入库
                //sku_id ware_id stock
                PurchaseDetailEntity finishedDetail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(finishedDetail.getSkuId(), finishedDetail.getWareId(), finishedDetail.getSkuNum());
            }
            updates.add(purchaseDetailEntity);
        }

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVO.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());

        this.updateById(purchaseEntity);
        purchaseDetailService.updateBatchById(updates);
    }

}